package api

import (
	"api/app/logs/documents"
	"api/config/code"
	"api/libs/api"
	"api/libs/morm"
	"fmt"
	"gitee.com/dreamwood/ez"
	"gitee.com/dreamwood/ez/server"
	"go.mongodb.org/mongo-driver/bson/primitive"
)

type EZRequestLogApi struct {
	api.BaseApi
}

func (c *EZRequestLogApi) Prepare() {
	c.RoutePrefix = fmt.Sprintf("/logs/admin/%s", "EZRequestLog")
	// 必要步骤
	c.SetBefore(func(operation *server.Operation) {
		// 执行此方法前operation 已经赋值到BaseApi.Operation
	})
}

func (c *EZRequestLogApi) SaveAction(operation *server.Operation) {
	this := c.TakeOver(operation)
	factory := morm.NewFactory()
	model := new(documents.EZRequestLog)
	if this.Try(this.FillJson(model)) {
		return
	}
	factory.TriggerNew(model)
	if model.Id.IsZero() {
		if this.Try(factory.Create(model)) {
			return
		}
	} else {
		if this.Try(factory.Update(model)) {
			return
		}
	}
	this.ReturnSuccess("保存成功", model)
}

func (c *EZRequestLogApi) GetAction(operation *server.Operation) {
	this := c.TakeOver(operation)
	factory := morm.NewFactory()
	model := new(documents.EZRequestLog)
	id := this.Get(`id`).IsString()
	if this.Try(factory.Find(model, id)) {
		return
	}
	this.ReturnSuccess("OK", model)
}

func (c *EZRequestLogApi) ListAction(operation *server.Operation) {
	this := c.TakeOver(operation).GetHttpQuery()
	factory := morm.NewFactory()
	list := make([]*documents.EZRequestLog, 0)
	factory.SetDoc(&documents.EZRequestLog{})
	e := factory.FindBy(&list, this.HttpQuery)
	if this.Try(e) {
		return
	}
	count, e := factory.Count(this.HttpQuery)
	if this.Try(e) {
		return
	}
	outPut := server.NewJsonOut(code.Success, "列表获取成功", ez.M{
		"lists": list,
		"query": ez.M{"page": this.HttpQuery.Page, "limit": this.HttpQuery.Limit, "total": count},
	})
	this.JsonOut(outPut)
}

func (c *EZRequestLogApi) DeleteAction(operation *server.Operation) {
	this := c.TakeOver(operation)
	factory := morm.NewFactory()
	id := operation.Get(`id`).IsString()
	oid, e := primitive.ObjectIDFromHex(id)
	if this.Try(e) {
		return
	}
	if this.Try(factory.Delete(&documents.EZRequestLog{Id: oid})) {
		return
	}
	this.ReturnSuccess("删除成功", "")
}
